package com.yonyou.common.service.messagecenter.interceptor;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.yonyou.common.service.messagecenter.dao.TtAppKeyMapper;
import com.yonyou.common.service.messagecenter.rabbitmq.entity.TtAppKey;
import com.yonyou.common.service.messagecenter.rabbitmq.entity.TtMessageHistoryConsumer;
import com.yonyou.common.service.messagecenter.util.Md5Utils;
import com.yonyou.common.service.messagecenter.util.MqConsts;

import net.sf.json.JSONArray;
import tk.mybatis.mapper.entity.Example;

public class MessageAuthCheckInterceptor implements HandlerInterceptor{

	@Autowired
	private TtAppKeyMapper ttAppKeyMapper;
	@Override
	public boolean preHandle(HttpServletRequest req,
			HttpServletResponse res, Object handler) throws Exception {
		System.out.println("------getQueryString:"+req.getQueryString());
		Map<String,String> map=new HashMap<String,String>();
		boolean pcheck=parseParam(map,req);
		if(!pcheck) {
			returnParamError(res);
			return false;
		}
		boolean scheck=signCheck(map);
		if(!scheck){
			returnSignError(res);
			return false;
		}
		return true;
			
	}
	private boolean signCheck(Map<String,String> map){
		String appid=map.get("appid");
		String sign=map.get("sign");
		String nonce=map.get("nonce");
		String occurtime=map.get("occurtime");
		String key=this.findKey(appid);
		if("".equals(key)) 
			return false;
		String tmp=Md5Utils.getMD5(key+nonce+occurtime).toLowerCase();
		if(tmp.equals(sign)) return true;
		return false;
	}
	private boolean parseParam(Map<String,String> map,HttpServletRequest req){
		String[] data=req.getQueryString().split("&");
		String appid=getParam("appid",data);
		String sign=getParam("sign",data);
		String nonce=getParam("nonce",data);
		String occurtime=getParam("occurtime",data);
		if(appid==null || "".equals(appid)) return false;
		if(sign==null || "".equals(sign)) return false;
		if(nonce==null || "".equals(nonce)) return false;
		if(occurtime==null || "".equals(occurtime)) return false;
		map.put("appid", appid);
		map.put("sign", sign);
		map.put("nonce", nonce);
		map.put("occurtime", occurtime);
		return true;
	}
	private void writeResponse(HttpServletResponse res,String data){
		res.setCharacterEncoding("UTF-8");
		res.setContentType("application/json; charset=utf-8");
		try {
			res.getWriter().write(data);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	private void returnKeyError(HttpServletResponse res){
		Map<String,String> map=new HashMap<String,String>();
		map.put(MqConsts.RESPONSE_DATA_CODE, MqConsts.RESPONSE_DATA_VALUE_INTEL_ERROR);
		map.put(MqConsts.RESPONSE_DATA_MESSAGE, MqConsts.RESPONSE_DATA_VALUE_INTEL_ERROR_MESSAGE);
		JSONArray jarr=JSONArray.fromObject(map);
		writeResponse(res,jarr.toString());
	}
	private void returnParamError(HttpServletResponse res){
		Map<String,String> map=new HashMap<String,String>();
		map.put(MqConsts.RESPONSE_DATA_CODE, MqConsts.RESPONSE_DATA_VALUE_PARAM_LACK);
		map.put(MqConsts.RESPONSE_DATA_MESSAGE, MqConsts.RESPONSE_DATA_VALUE_PARAM_LACK_MESSAGE);
		JSONArray jarr=JSONArray.fromObject(map);
		writeResponse(res,jarr.toString());
	}
	private void returnSignError(HttpServletResponse res){
		Map<String,String> map=new HashMap<String,String>();
		map.put(MqConsts.RESPONSE_DATA_CODE, MqConsts.RESPONSE_DATA_VALUE_REQUEST_ERROR);
		map.put(MqConsts.RESPONSE_DATA_MESSAGE, MqConsts.RESPONSE_DATA_VALUE_REQUEST_ERROR_MESSAGE);
		JSONArray jarr=JSONArray.fromObject(map);
		writeResponse(res,jarr.toString());
	}
	private String findKey(String appid){
    	Example example = new Example(TtAppKey.class);
    	example.createCriteria().andCondition("appid=", appid);
    	List<TtAppKey> records=ttAppKeyMapper.selectByExample(example);
		if(records.size()!=1){
			return "";
		}
		return records.get(0).getAppkey();
	}
	private String getParam(String name,String[] queryString){
		for(String s:queryString){
			String[] kv=s.split("=");
			if(kv[0].equals(name))
				return kv[1];
		}
		return "";
	}
	public String readStream(InputStream inStream) throws Exception {  
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();  
        byte[] buffer = new byte[1024];  
        int len = -1;  
        while ((len = inStream.read(buffer)) != -1) {  
            outSteam.write(buffer, 0, len);  
        }  
        outSteam.close();  
        inStream.close();  
        
        return outSteam.toString();  
    } 
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest req,
			HttpServletResponse res, Object handler, Exception ex)
			throws Exception {
	}
}
